package com.act;

import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.Header;
import org.apache.http.message.BasicNameValuePair;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.Enum.InfoType;
import com.bean.SearchItem;
import com.bean.SearchResult;
import com.common.Constant;
import com.common.TextHttpResponseHandler;
import com.xike.kyt.R;
import com.xike.util.MLog;
import com.xike.util.MyUtil;
import com.xike.util.StringUtil;

public class SearchAct extends BaseAct implements OnClickListener {

	EditText edt_keyword;
	LinearLayout layout_input, layout_result;

	SearchResult searchResult;
	String strKeyword;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.act_search);
		initViews();
	}

	@Override
	protected void initViews() {

		findViewById(R.id.search_tv_cancel).setOnClickListener(this);

		layout_input = (LinearLayout) findViewById(R.id.search_layout_input);
		edt_keyword = (EditText) findViewById(R.id.search_edt_keyword);

		edt_keyword.setSingleLine(true); // android:singleLine=”true”
		edt_keyword.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
		edt_keyword.setOnEditorActionListener(new TextView.OnEditorActionListener() {
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
				if (actionId == EditorInfo.IME_ACTION_SEARCH || (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
					if (layout_result.getChildCount() > 0) {
						layout_result.removeAllViews();
					}
					serviceSearch();
					return true;
				}
				return false;
			}
		});

		layout_result = (LinearLayout) findViewById(R.id.search_layout_result);
		findViewById(R.id.search_img_clear).setOnClickListener(this);

	}

	@Override
	protected void updateViews() {
		ArrayList<SearchItem> items = searchResult.getSearch();
		if (items == null || items.size() == 0) {
			mToast.showToast(this, "暂无相关内容");
			return;
		}

		MyAdapter adapter;
		for (final SearchItem item : items) {
			if (item.getInfo_type() != InfoType.People.getIntValue() && item.getInfo_type() != InfoType.Answer.getIntValue() && item.getInfo_type() != InfoType.Question.getIntValue()) {
				continue;// 过滤不支持的结果样式 目前支持问题、答案、人物。
			}
			LinearLayout layout_item = (LinearLayout) View.inflate(this, R.layout.layout_search_item, null);
			TextView tv_lable = (TextView) layout_item.findViewById(R.id.item_search_tv_lable);

			ListView searchitem_listview = (ListView) layout_item.findViewById(R.id.item_search_listview);
			adapter = new MyAdapter(item.getInfo_type(), item.getResults());
			searchitem_listview.setAdapter(adapter);

			MyUtil.setListViewHeightBasedOnChildren(searchitem_listview);

			searchitem_listview.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
					if (item.getInfo_type() == InfoType.People.getIntValue()) {
						Intent it_userInfo = new Intent(SearchAct.this, UserInfoAct.class);
						it_userInfo.putExtra("userId", item.getResults().get(position).getUser_id());
						startActivity(it_userInfo);
					} else if (item.getInfo_type() == InfoType.Question.getIntValue()) {
						Intent it_question = new Intent(SearchAct.this, Question_DetailAct.class);
						it_question.putExtra("questionId", item.getResults().get(position).getInfo_id());
						startActivity(it_question);
					} else if (item.getInfo_type() == InfoType.Answer.getIntValue()) {
						Intent it_question = new Intent(SearchAct.this, Answer_DetailAct.class);
						it_question.putExtra("answerId", item.getResults().get(position).getInfo_id());
						startActivity(it_question);
					}
				}
			});

			tv_lable.setText("相关" + InfoType.getByIntValue(item.getInfo_type()).toString());
			layout_result.addView(layout_item);
		}
		layout_result.setVisibility(View.VISIBLE);
		layout_input.setVisibility(View.GONE);

	}

	private void serviceSearch() {

		strKeyword = MyUtil.getEditTextContent(edt_keyword);
		ArrayList<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
		params.add(new BasicNameValuePair("keyword", strKeyword));

		String strUrl = MyUtil.signRequestUrl(Constant.SERVER_URL_SEARCH, params);
		client.get(this, strUrl, new TextHttpResponseHandler(this) {

			@Override
			public void onSuccess(int statusCode, Header[] headers, String responseString) {
				SearchResult result = gson.fromJson(responseString, SearchResult.class);
//				MLog.e("serviceSearch", "result:" + responseString);
				dealRequestResult(result);
				super.onSuccess(statusCode, headers, responseString);
			}

			@Override
			public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
				mToast.showToast(SearchAct.this, getResources().getString(R.string.net_error));
				super.onFailure(statusCode, headers, responseString, throwable);
			}
		});
	}

	private void dealRequestResult(SearchResult result) {
		if (result != null) {
			if (result.getError_code().equals(Constant.RESULT_CODE_SUCCESS)) {
				searchResult = result;
				updateViews();
			} else {
				mToast.showToast(this, result.getError_description());
			}
		} else {
			mToast.showToast(this, getString(R.string.net_error));
		}
	}

	private SpannableString getSpannable(String text, String keyWord) {
		SpannableString s = new SpannableString(text);
		Pattern p = Pattern.compile(keyWord);
		Matcher m = p.matcher(s);
		while (m.find()) {
			int start = m.start();
			int end = m.end();
			s.setSpan(new ForegroundColorSpan(Color.parseColor("#00ba00")), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
		}
		return s;
	}

	class MyAdapter extends BaseAdapter {

		int info_type;
		ArrayList<SearchItem.Result> searchItem_results = new ArrayList<SearchItem.Result>();

		public MyAdapter(int info_type, ArrayList<SearchItem.Result> searchItem_results) {
			this.info_type = info_type;
			this.searchItem_results = searchItem_results;
		}

		@Override
		public int getCount() {
			return searchItem_results.size();
		}

		@Override
		public SearchItem.Result getItem(int position) {
			return searchItem_results.get(position);
		}

		@Override
		public long getItemId(int position) {
			return searchItem_results.get(position).getInfo_id();
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			final ViewHolder holder;
			if (convertView == null) {
				convertView = View.inflate(SearchAct.this, R.layout.listitem_search, null);
				holder = new ViewHolder();
				holder.layout_people = (RelativeLayout) convertView.findViewById(R.id.lvitem_search_layout_people);
				holder.layout_question = (LinearLayout) convertView.findViewById(R.id.lvitem_search_layout_question);

				holder.tv_userName = (com.mUI.MeasureTextView) convertView.findViewById(R.id.user_tv_name);
				holder.tv_userDesc = (com.mUI.MeasureTextView) convertView.findViewById(R.id.user_tv_desc);
				holder.img_userAvator = (ImageView) convertView.findViewById(R.id.user_img_image);

				holder.tv_questionDesc = (com.mUI.MeasureTextView) convertView.findViewById(R.id.lvitem_search_tv_questionDesc);
				holder.tv_questionTitle = (com.mUI.MeasureTextView) convertView.findViewById(R.id.lvitem_search_tv_questionTitle);

				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}

			SearchItem.Result result = getItem(position);
			if (info_type == InfoType.People.getIntValue()) {
				holder.layout_people.setVisibility(View.VISIBLE);
				holder.layout_question.setVisibility(View.GONE);

				String strName = result.getUser_name();
				if (StringUtil.isNotNull(strName)) {
					holder.tv_userName.setText(getSpannable(strName, strKeyword));
				}

				String strDesc = result.getContent();
				if (StringUtil.isNotNull(strDesc)) {
					holder.tv_userDesc.setText(getSpannable(strDesc, strKeyword));
				} else {
					holder.tv_userDesc.setText("暂无简介");
				}

				BitmapDrawable defualtdrawable = (BitmapDrawable) getResources().getDrawable(R.drawable.default_user_avator);
				Bitmap defaultBitmap = defualtdrawable.getBitmap();
				MyUtil.displayImageView(SearchAct.this, result.getUser_avator(), holder.img_userAvator, defaultBitmap, true);
			} else if (info_type == InfoType.Question.getIntValue() || info_type == InfoType.Answer.getIntValue()) {
				holder.layout_question.setVisibility(View.VISIBLE);
				holder.layout_people.setVisibility(View.GONE);

				String strTitle = result.getTitle();
				if (StringUtil.isNotNull(strTitle)) {
					holder.tv_questionTitle.setText(getSpannable(strTitle, strKeyword));
				}

				String strDesc = result.getContent();
				if (StringUtil.isNotNull(strDesc)) {
					holder.tv_questionDesc.setText(getSpannable(strDesc, strKeyword));
				} else {
					holder.tv_questionDesc.setVisibility(View.GONE);
				}

			}

			return convertView;
		}

		class ViewHolder {
			RelativeLayout layout_people;
			LinearLayout layout_question;
			com.mUI.MeasureTextView tv_questionTitle, tv_questionDesc;

			com.mUI.MeasureTextView tv_userName, tv_userDesc;
			ImageView img_userAvator;
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.search_img_clear:
			if (layout_result.getChildCount() > 0) {
				layout_result.removeAllViews();
				layout_input.setVisibility(View.VISIBLE);
				layout_result.setVisibility(View.GONE);
			}
			edt_keyword.setText("");

			break;
		case R.id.search_tv_cancel:
			finish();
			break;
		default:
			break;
		}
	}
}
